<template>
  <div id="ProvinceMap" ref="main" style="width: 100%; height: 100%;">

  </div>
</template>

<script>
import { getData1} from "@/api/component";

export default {
  name: 'ProvinceMap',
  props: ["dataFromParent"],
  data () {
    return {
      searchText:'',
      chart: null,
      mapData: [],
    };
  },
  watch: {
    dataFromParent(newVal) {
      this.dataFromP(newVal);
    }
  },

  mounted() {
    // this.showDetails();
  },
  computed: {
    // 计算属性，依赖于 mapData
    completedDataArray: {
      get() {
        const withCode = this.mapData.filter(item => item.code !== undefined);
        const withoutCode = this.mapData.filter(item => item.code === undefined);

        const codeMap = new Map(withCode.map(item => [item.name, item.code]));

        const updatedWithoutCode = withoutCode.map(item => {
          const code = codeMap.get(item.name);
          return { ...item, code: code !== undefined ? code : null };
        });

        return [...updatedWithoutCode, ...withCode];
      },
      // 如果需要，可以在这里设置一个 setter 函数
      // set(newValue) {
      //   this.mapData = newValue;
      // }
    }
  },
  methods: {
    refresh(){
      this.dataFromP(this.dataFromParent);
    },
    dataFromP(newVal) {
      getData1(parseInt(newVal.code)).then(res => {
        if (res.code == 200) {
          this.mapData = res.data.map(item => {
            return {
              ...item,
              name: item.name.endsWith('市') ? item.name.slice(0, -1) : item.name
            };
          });

          if (newVal && newVal.code) {
            this.showDetails().then(() => {
              this.hightLight(newVal.select);
            }).catch(error => {
              console.error('Error in showDetails or hightLight:', error);
            });
          }

        }
      });

    },
    async showDetails() {
    var ROOT_PATH = `https://geojson.cn/api/china/${this.dataFromParent.code}.json`;
    var chartDom = this.$refs.main;
    if (!chartDom) {
      console.error('无法找到 DOM 元素：ref="main"');
      return;
    }
    if (this.chart) {
      // 如果已经初始化了图表实例，先销毁它
      this.chart.dispose();
    }
    var myChart = this.$echarts.init(chartDom);
    this.chart = myChart;
    myChart.showLoading();

    try {
      const response = await fetch(ROOT_PATH);
      if (!response.ok) {
        throw new Error('地图数据加载失败');
      }
      const geoJson = await response.json();
      this.$echarts.registerMap(this.dataFromParent.name, geoJson);
          var option = {
            title: {
              text: this.dataFromParent.name,
              left: 'center',
              textStyle: {
                color: '#fff'
              }
            },
            series: [
              {
                type: 'map',
                mapType:this.dataFromParent.name,
                roam: true,
                zoom: 1,
                label: {
                  show: true,
                  color: '#fff'
                },
                itemStyle: {
                  areaColor: '#2b4a6e',
                  borderColor: '#fff',
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                  shadowBlur: 10
                },
                emphasis: {
                  itemStyle: {
                    areaColor: 'yellow'
                  }
                },
                data:this.mapData,

              }
            ]
          };

          myChart.setOption(option);
      myChart.hideLoading();
    } catch (error) {
      console.error('地图数据加载错误：', error);
      myChart.hideLoading();
    }
  },
  async hightLight(newVal) {
    await this.showDetails(); // 等待 showDetails 完成
    this.highlightProvince(newVal); // 然后执行高亮逻辑
  },
  highlightProvince(newVal) {
    this.searchText = newVal;
    if (this.searchText && this.chart) {
      this.chart.dispatchAction({ type: 'downplay', seriesIndex: 0 });
      this.mapData=this.chart.getOption().series[0].data;
      this.chart.getOption().series[0].data=this.completedDataArray;
      const seriesData = this.chart.getOption().series[0].data;
      console.log(seriesData)
      const target = seriesData.find((item) => item.code && item.code == this.searchText);
      if (target) {
        this.chart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          name: target.name
        });
        this.$emit('city', target);
      } else {
        alert('省份名称输入错误或不存在');
      }
      this.searchText = '';
    }
  }
  }
};
</script>

<style lang='scss' scoped>
</style>
